<script setup>
import { ref, onMounted, nextTick } from "vue";
import { useRoute } from "vue-router";
import {
  showSuccessToast,
  showFailToast,
  showToast,
  showLoadingToast,
  showConfirmDialog,
} from "vant";
import {
  sendSmsCodeApi,
  sendRobotMessageApi,
  uploadFilesApi,
} from "@/request/api";
import { useI18n } from "vue-i18n";
const { t, locale } = useI18n();

const route = useRoute();
const lang = ref(locale.value);
const formRef = ref(null);
const smsText = ref(t("sendVerificationCode"));
const messageId = ref("");
const caseInfoVisible = ref(false);
const yearPopVisible = ref(false);
const wordPopVisible = ref(false);
const collectNoError = ref("");
const caseNoError = ref("");
const regCaseNo = /^[a-zA-Z0-9]{1,5}$/; // 不超过5位, 不包含中文, 不可有空格与特殊字符
const regCollectNo = /^[a-zA-Z0-9\-]{1,20}$/; // 不超过20位, 可包含横杆(-), 不包含中文, 不可有空格与特殊字符
const confirmText = ref(t("confirmText"));
const canceltext = ref(t("canceltext"));
const wordColumns = [
  { text: t("suiZhongCase"), value: "穗仲案字第" },
  { text: t("suiZhongInternetCase"), value: "穗仲网案字第" },
  { text: t("suiZhongZhongCase"), value: "穗仲中案字第" },
  { text: t("suiZhongGuanCase"), value: "穗仲莞案字第" },
];
let form = ref({
  name: "",
  idType: "身份证",
  idNumber: "",
  email: "",
  phone: "",
  verifyCode: "",
  guid: "",
  letterType: "1",
  letterContents: "",
  caseNo: "",
});
const fileList = ref([]);
let caseInfo = ref({
  caseType: "2",
  caseYear: [new Date().getFullYear()],
  caseWord: [t("suiZhongCase")],
  caseNo: "",
  collectNo: "",
});

onMounted(async () => {});

const countDown = () => {
  const times = setInterval(() => {
    if (smsText.value === 0) {
      clearInterval(times);
      smsText.value = t("sendVerificationCode");
      return;
    } else if (smsText.value === t("sendVerificationCode")) {
      smsText.value = 59;
    } else {
      smsText.value--;
    }
  }, 1000);
};
const letterTypeChange = (e) => {
  caseInfoVisible.value = e === "0";
};
const onYearConfirm = (e) => {
  caseInfo.value.caseYear = e.selectedValues;
  yearPopVisible.value = false;
};
const onWordConfirm = (e) => {
  // caseInfo.value.caseWord = e.selectedValues;
  caseInfo.value.caseWord = [e.selectedOptions[0].text];
  wordPopVisible.value = false;
};
const collectNoChange = (e) => {
  caseInfo.value.collectNo = e.replace(/\s+/g, '');
  if (caseInfo.value.collectNo && !regCollectNo.test(caseInfo.value.collectNo)) {
    collectNoError.value = t("field_receivingNo_verify");
  } else {
    collectNoError.value = "";
  }
};
const caseNoChange = (e) => {
  caseInfo.value.caseNo = e.replace(/\s+/g, '');
  if (caseInfo.value.caseNo && !regCaseNo.test(caseInfo.value.caseNo)) {
    caseNoError.value = t("field_caseNo_verify");
  } else {
    caseNoError.value = "";
  }
};
const sendSms = () => {
  const { idNumber, phone } = form.value;
  if (!idNumber) {
    showToast(t("field_idCard_placeholder"));
    return;
  }
  if (phone) {
    const data = { idCard: idNumber, phone: phone };
    sendSmsCodeApi(data).then((res) => {
      if (res.result === "200" && res.data) {
        countDown();
        form.value.guid = res.data;
        showSuccessToast(t("verificationCodeSent"));
      }
    });
  } else {
    showToast(t("beforeProceeding"));
  }
};
const onOversize = () => {
  showToast(t("field_filesUpload_sizeMax", { size: 10 }));
};
const resetForm = () => {
  form.value = {
    name: "",
    idType: "身份证",
    idNumber: "",
    email: "",
    phone: "",
    verifyCode: "",
    guid: "",
    letterType: "1",
    letterContents: "",
    caseNo: "",
  };
  caseInfo.value = {
    caseType: "2",
    caseYear: [new Date().getFullYear()],
    caseWord: [t("suiZhongCase")],
    caseNo: "",
    collectNo: "",
  };
  // nextTick(() => {
  //   formRef.value.resetValidation();
  // });
  setTimeout(() => {
    formRef.value.resetValidation();
  }, 500);
  // router.push({
  //   path: `/home`,
  // });
};
const onSubmit = (val) => {
  let formData = JSON.parse(JSON.stringify(form.value));
  if (form.value.letterType === "0") {
    // 案件详情
    if (caseInfo.value.caseType === "2" && !caseInfo.value.collectNo) {
      // 收案号
      // showFailToast(t("caseReceivingNo_placeholder"));
      showToast(t("caseReceivingNo_placeholder"));
      return;
    } else if (
      caseInfo.value.caseType === "2" &&
      caseInfo.value.collectNo &&
      collectNoError.value !== ""
    ) {
      showToast(t("field_receivingNo_verify"));
      return;
    } else if (caseInfo.value.caseType === "2" && caseInfo.value.collectNo) {
      formData.caseNo = caseInfo.value.collectNo;
    }
    if (caseInfo.value.caseType === "1" && !caseInfo.value.caseNo) {
      // 案号
      // showFailToast(t("caseNo_placeholder"));
      showToast(t("caseNo_placeholder"));
      return;
    } else if (
      caseInfo.value.caseType === "1" &&
      caseInfo.value.caseNo &&
      caseNoError.value !== ""
    ) {
      showToast(t("field_caseNo_verify"));
      return;
    } else if (caseInfo.value.caseType === "1" && caseInfo.value.caseNo) {
      formData.caseNo = `${caseInfo.value.caseYear[0]}-${caseInfo.value.caseNo}`;
      formData.caseType = wordColumns.find(item => item.text === caseInfo.value.caseWord[0]).value;
    }
  }

  // console.log(formData, "......formData");
  // console.log(fileList.value, "......fileList");
  // return;
  showLoadingToast(t("submitting"));
  sendRobotMessageApi(formData).then((res) => {
    if (res && (res.code === 0 || res.result === "200")) {
      if(res.data) {
        messageId.value = res.data;
        showSuccessToast(t("messageSent"));
        if (fileList.value.length > 0) {
          uploadFile(res.data);
        } else {
          resetForm();
        }
      } else {
        showToast(t("notFoundCase"));
      }
    }
  });
};
const uploadFile = (id) => {
  let formData = new FormData();
  fileList.value.map((item) => {
    formData.append("files", item.file);
  });
  formData.append("id", id);

  showLoadingToast(t("fileUploading"));
  uploadFilesApi(formData).then((res) => {
    if (res && (res.code === 0 || res.result === "200")) {
      showSuccessToast(t("fileUploaded"));
      fileList.value = [];
      resetForm();
    }
  });
};
</script>

<template>
  <div class="message">
    <van-form ref="formRef" class="form" required="auto" @submit="onSubmit">
      <div class="formBox">
        <van-field
          v-model="form.name"
          name="name"
          :label="$t('field_name')"
          :placeholder="$t('field_name_placeholder')"
          :rules="[
            {
              required: true,
              message: $t('field_name_placeholder'),
              trigger: ['onChange', 'onBlur'],
            },
          ]"
        />
        <van-field
          v-model="form.idNumber"
          name="idNumber"
          :label="$t('field_idCard')"
          :placeholder="$t('field_idCard_placeholder')"
          :rules="[
            {
              required: true,
              message: $t('field_idCard_placeholder'),
              trigger: ['onChange', 'onBlur'],
            },
            // {
            //   pattern:
            //     /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/,
            //   message: $t('field_idCard_verify'),
            //   trigger: ['onChange', 'onBlur'],
            // },
          ]"
        />
        <van-field
          class="unRequiredSpace"
          v-model="form.email"
          name="email"
          :label="$t('field_mailbox')"
          :placeholder="$t('field_mailbox_placeholder')"
          :rules="[
            {
              required: false,
              message: $t('field_mailbox_placeholder'),
              trigger: ['onChange', 'onBlur'],
            },
            {
              pattern:
                /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
              message: $t('field_mailbox_verify'),
              trigger: ['onChange', 'onBlur'],
              validateEmpty: false,
            },
          ]"
        />
        <van-field
          v-model="form.phone"
          name="phone"
          :label="$t('field_cellphone')"
          :placeholder="$t('field_cellphone_placeholder')"
          :rules="[
            {
              required: true,
              message: $t('field_cellphone_placeholder'),
              trigger: ['onChange', 'onBlur'],
            },
            {
              pattern:
                /^1(3[0-9]|4[01456879]|5[0-3,5-9]|6[2567]|7[0-8]|8[0-9]|9[0-3,5-9])\d{8}$/,
              message: $t('field_cellphone_verify'),
              trigger: ['onChange', 'onBlur'],
            },
          ]"
        >
          <template #button>
            <van-button
              class="smsBtn"
              size="small"
              type="primary"
              @click="sendSms"
              :disabled="smsText !== $t('sendVerificationCode')"
              >{{ smsText }}</van-button
            >
          </template>
        </van-field>
        <van-field
          v-model="form.verifyCode"
          name="verifyCode"
          :label="$t('field_verificationCode')"
          :placeholder="$t('field_verificationCode_placeholder')"
          :rules="[
            {
              required: true,
              message: $t('field_verificationCode_placeholder'),
              trigger: ['onChange', 'onBlur'],
            },
          ]"
        />
        <van-field
          v-model="form.letterType"
          name="letterType"
          :label="$t('field_messageType')"
          :placeholder="$t('field_messageType_placeholder')"
          :rules="[
            {
              required: true,
              message: $t('field_messageType_placeholder'),
              trigger: ['onChange', 'onBlur'],
            },
          ]"
        >
          <template #input>
            <van-radio-group
              v-model="form.letterType"
              direction="horizontal"
              @change="letterTypeChange"
            >
              <van-radio :class="[lang === 'en' ? 'margin_b8' : '']" name="0">{{
                $t("field_caseSituation")
              }}</van-radio>
              <van-radio name="1">{{ $t("field_suggestion") }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <div v-if="caseInfoVisible" class="caseInfo">
          <!-- <van-radio-group v-model="caseInfo.caseType">
            <van-cell-group inset>
              <van-cell
                title="收案号"
                clickable
                @click="caseInfo.caseType = '2'"
              >
                <template #right-icon>
                  <van-radio name="2" />
                </template>
              </van-cell>
              <van-cell title="案号" clickable @click="caseInfo.caseType = '1'">
                <template #right-icon>
                  <van-radio name="1" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-radio-group> -->
          <van-field
            class="unRequiredSpace"
            v-model="caseInfo.caseType"
            name="letterType"
            :label="$t('numberType')"
            placeholder="请选择案号类型"
          >
            <template #input>
              <van-radio-group
                v-model="caseInfo.caseType"
                direction="horizontal"
              >
                <van-radio
                  :class="[lang === 'en' ? 'margin_b8' : '']"
                  name="2"
                  >{{ $t("caseReceivingNo") }}</van-radio
                >
                <van-radio name="1">{{ $t("caseNo") }}</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            v-if="caseInfo.caseType === '2'"
            v-model="caseInfo.collectNo"
            :placeholder="$t('caseReceivingNo_placeholder')"
            @update:model-value="collectNoChange"
            :error-message="collectNoError"
          />
          <div class="caseNoItem" v-if="caseInfo.caseType === '1'">
            <div class="caseYear" @click="yearPopVisible = true">
              {{ caseInfo.caseYear[0] }}
              <van-icon name="arrow-down" />
            </div>
            <div class="caseWord" @click="wordPopVisible = true">
              {{ caseInfo.caseWord[0] }}
              <van-icon name="arrow-down" />
            </div>
            <van-field
              class="caseNo"
              v-model="caseInfo.caseNo"
              :placeholder="$t('caseNo_placeholder')"
              @update:model-value="caseNoChange"
            />
          </div>
          <div
            v-if="caseInfo.caseType === '1' && caseNoError"
            class="caseNoError"
          >
            {{ caseNoError }}
          </div>
          <div class="caseInfoDesc">
            <div class="caseInfoDescInner">
              <van-icon class="icon" name="warning" />
              <div class="cnt">
                <div>
                  {{ $t("receivingNoRemark") }}
                </div>
                <div>
                  {{ $t("caseNoRemark") }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <van-field
          v-model="form.letterContents"
          name="letterContents"
          :label="$t('field_message')"
          type="textarea"
          maxlength="500"
          show-word-limit
          rows="5"
          autosize
          :placeholder="$t('field_message_placeholder')"
          :rules="[
            {
              required: true,
              message: $t('field_message_placeholder'),
              trigger: ['onChange', 'onBlur'],
            },
          ]"
        />
        <van-field
          class="unRequiredSpace"
          name="uploader"
          :label="$t('field_filesUpload')"
        >
          <template #input>
            <div class="uploadBox">
              <van-uploader
                multiple
                :max-count="3"
                :max-size="10 * 1024 * 1024"
                accept=".doc,.docx,.pdf,.ppt,.pptx,.xlsx,.xls,image/*"
                v-model="fileList"
                @oversize="onOversize"
              />
              <div class="uploadTips">
                * {{ $t("field_filesUpload_max", { size: 3 }) }}
              </div>
            </div>
          </template>
        </van-field>
      </div>

      <div class="btn">
        <van-button round block type="primary" native-type="submit">
          {{ $t("submitTheMessage") }}
        </van-button>
      </div>
    </van-form>

    <van-popup
      v-model:show="yearPopVisible"
      position="bottom"
      :style="{ height: '40%' }"
    >
      <van-date-picker
        :title="$t('selectCaseYear')"
        v-model="caseInfo.caseYear"
        :min-date="new Date(1995, 0, 1)"
        :max-date="new Date(new Date().getFullYear(), 0, 1)"
        :columns-type="['year']"
        :confirm-button-text="confirmText"
        :cancel-button-text="canceltext"
        @confirm="onYearConfirm"
        @cancel="yearPopVisible = false"
      />
    </van-popup>
    <van-popup
      v-model:show="wordPopVisible"
      position="bottom"
      :style="{ height: '40%' }"
    >
      <van-picker
        :title="$t('selectCaseWord')"
        :columns="wordColumns"
        :confirm-button-text="confirmText"
        :cancel-button-text="canceltext"
        @confirm="onWordConfirm"
        @cancel="wordPopVisible = false"
      />
    </van-popup>
  </div>
</template>

<style lang="less" scoped>
.message {
  height: 100%;
  background: url("/public/img/mobile/bg-empty.png") no-repeat bottom center;
  background-color: rgba(255, 255, 255, 0.5);
  background-size: cover;
  padding: 10px;
  box-sizing: border-box;
  overflow: auto;
  .form {
    width: 100%;
  }
  .formBox {
    border-radius: 8px;
    overflow: hidden;
  }
  // .unRequiredSpace {
  //   :deep(.van-field__label) {
  //     label {
  //       margin-left: 10px;
  //     }
  //   }
  // }
  .caseInfo {
    width: 100%;
    background: #fff;
    .caseNoItem {
      padding: 0px 10px 0 25px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .caseYear {
        // width: 110px;
        flex: 2;
        font-size: 14px;
        color: #333;
        cursor: pointer;
      }
      .caseWord {
        // width: 200px;
        flex: 3;
        font-size: 14px;
        color: #333;
        cursor: pointer;
      }
      .caseNo {
        flex: 3;
      }
    }
    .caseNoError {
      padding: 0 10px;
      color: var(--van-field-error-message-color);
      font-size: var(--van-field-error-message-font-size);
      margin-bottom: 10px;
    }
    .caseInfoDesc {
      padding: 10px;
      box-sizing: border-box;
      .caseInfoDescInner {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        gap: 10px;
        padding: 10px;
        box-sizing: border-box;
        background: #e6f7ff;
        border-radius: 8px;
        .icon {
          font-size: 24px;
          color: #1989fa;
        }
        .cnt {
          font-size: 14px;
          color: #333;
        }
      }
    }
  }
  .smsBtn {
    width: 80px;
  }
  .btn {
    margin: 16px;
  }
  .uploadBox {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
    .uploadTips {
      font-size: 14px;
      color: #999;
      background: #fff;
    }
  }
  .outBox {
    width: 90%;
    height: 90%;
    margin: auto;
    background: url("/public/img/exhibition-bg.png") no-repeat center center;
    -webkit-background-size: 100% 100%;
    -o-background-size: 100% 100%;
    background-size: 100% 100%;
    @media only screen and (orientation: landscape) {
      // 横向
      width: calc(100vw * 0.7);
      height: calc(100vw * 0.7 * 0.625);
    }
  }
}
</style>
